package com.example.remotecontrol.ui.devices

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.remotecontrol.data.model.Device
import com.example.remotecontrol.ui.components.DeviceCard

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DevicesScreen(
    viewModel: DevicesViewModel = hiltViewModel(),
    onNavigateToDeviceDetail: (String) -> Unit = {},
    onNavigateToAddDevice: () -> Unit = {}
) {
    val viewMode by viewModel.viewMode.collectAsState()
    val searchQuery by viewModel.searchQuery.collectAsState()
    val filteredDevices by viewModel.filteredDevices.collectAsState()
    
    var showDeleteDialog by remember { mutableStateOf(false) }
    var deviceToDelete by remember { mutableStateOf<Device?>(null) }
    
    // 首次加载时创建一些示例设备（仅用于演示）
    LaunchedEffect(Unit) {
        if (viewModel.allDevices.value.isEmpty()) {
            viewModel.createSampleDevices()
        }
    }

    Scaffold(
        floatingActionButton = {
            FloatingActionButton(
                onClick = onNavigateToAddDevice,
                containerColor = MaterialTheme.colorScheme.primary
            ) {
                Icon(
                    imageVector = Icons.Default.Add,
                    contentDescription = "添加设备",
                    tint = MaterialTheme.colorScheme.onPrimary
                )
            }
        }
    ) { innerPadding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(innerPadding)
        ) {
            // 顶部选项卡
            TabRow(
                selectedTabIndex = viewMode.ordinal
            ) {
                DeviceViewMode.values().forEachIndexed { index, mode ->
                    Tab(
                        selected = viewMode.ordinal == index,
                        onClick = { viewModel.setViewMode(mode) },
                        text = {
                            Text(
                                text = when (mode) {
                                    DeviceViewMode.ALL -> "全部"
                                    DeviceViewMode.FAVORITES -> "收藏"
                                    DeviceViewMode.RECENT -> "最近"
                                }
                            )
                        }
                    )
                }
            }
            
            // 搜索框
            OutlinedTextField(
                value = searchQuery,
                onValueChange = { viewModel.setSearchQuery(it) },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp),
                placeholder = { Text("搜索设备...") },
                leadingIcon = { 
                    Icon(
                        imageVector = Icons.Default.Search,
                        contentDescription = null
                    )
                },
                singleLine = true
            )
            
            // 没有设备时的提示
            if (filteredDevices.isEmpty()) {
                Box(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(16.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text(
                            text = if (searchQuery.isNotBlank()) 
                                "没有找到匹配的设备" 
                            else 
                                "没有设备",
                            style = MaterialTheme.typography.titleMedium
                        )
                        
                        if (searchQuery.isBlank()) {
                            Spacer(modifier = Modifier.height(16.dp))
                            Button(
                                onClick = onNavigateToAddDevice
                            ) {
                                Text("添加设备")
                            }
                        }
                    }
                }
            } else {
                // 设备列表
                LazyColumn(
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(16.dp)
                ) {
                    items(filteredDevices) { device ->
                        DeviceCard(
                            device = device,
                            onClick = { 
                                // 更新设备使用时间并导航到设备详情页
                                viewModel.updateDeviceUsage(device.id)
                                onNavigateToDeviceDetail(device.id)
                            },
                            onEditClick = {
                                // 导航到设备编辑页
                                onNavigateToDeviceDetail(device.id)
                            },
                            onDeleteClick = {
                                deviceToDelete = device
                                showDeleteDialog = true
                            },
                            onFavoriteToggle = {
                                viewModel.toggleFavorite(device.id)
                            }
                        )
                    }
                }
            }
        }
    }
    
    // 删除确认对话框
    if (showDeleteDialog && deviceToDelete != null) {
        AlertDialog(
            onDismissRequest = { showDeleteDialog = false },
            title = { Text("删除设备") },
            text = { Text("确定要删除设备 \"${deviceToDelete?.name}\" 吗？此操作不可恢复。") },
            confirmButton = {
                TextButton(
                    onClick = {
                        deviceToDelete?.id?.let { deviceId ->
                            viewModel.deleteDevice(deviceId)
                        }
                        showDeleteDialog = false
                        deviceToDelete = null
                    }
                ) {
                    Text("确定")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        showDeleteDialog = false
                        deviceToDelete = null
                    }
                ) {
                    Text("取消")
                }
            }
        )
    }
} 